<template>
  <CommonTreeTable :data="data" :options="options" :table-cols="columns" ref="tableRef"/>
</template>

<script setup lang="ts">

import {
  useApi,
} from "~/composeables";
import {ref} from 'vue';
import UpdateDialog from "~/components/admin/Department/UpdateDialog.vue";
import CreateDialog from "~/components/admin/Department/CreateDialog.vue";
import DepartmentCache from "~/store/system/departmentCache";

const api = useApi()

const pageIndex = ref(1);
const pageSize = ref(10);
const filters = ref({});
const data = ref([]);
const tableRef= ref<any>();

const loadData = (pi : number = pageIndex.value, ps : number = pageSize.value, fs : any = filters.value)=> {
  api.systemDepartmentApi.getTreeData({pageIndex: pi, pageSize: ps})
      .then(res=>{
        data.value = res.data
      }).catch(err=>{
        console.error(err)
      })
}


const deleteOne = async (id:any)=>{
  await api.systemDepartmentApi.deleteById(id)
      .then(res=>{
        if(res.success){
          ElMessage.success("已成功删除！");
          forceReload();
        }else{
          ElMessage.error("删除失败");
        }
      })
      .catch(err=>{
        console.error(err);
        ElMessage.error("删除失败");
      })
}

const deleteMany = async (ids:any)=>{
  await api.systemDepartmentApi.deleteMany(ids)
      .then(res=>{
        if(res.success){
          ElMessage.success("已成功删除！");
          forceReload();
        }else{
          ElMessage.error("删除失败");
        }
      })
      .catch(err=>{
        console.error(err);
        ElMessage.error("删除失败");
      })
}

const options : ElTableOptions = {
  showTitle : true,
  title : "部门列表",
  allowEdit : true,
  allowDelete: true,
  allowDeleteMany : true,
  dataLoadFunc : loadData,
  deleteFunc : deleteOne,
  deleteManyFunc : deleteMany,
  updateDialog : UpdateDialog,
  createDialog : CreateDialog,
  filterList: [],
  orderList: [],
  pageSize: 10,
};

const getDepartmentName = (id : any)=>{
  let matched = DepartmentCache.departments?.filter(x=>x.id === id);
  if(matched?.length > 0){
    return matched[0].name;
  }else {
    return "/";
  }
}

const columns : Array<ElTableColumnSetting> = [
  {columnName: "name",columnVerboseName: "部门",columnWidth: 0, columnValueConverter: (value: any)=>value},
  {columnName: "parentId",columnVerboseName: "上级部门",columnWidth: 0, columnValueConverter: getDepartmentName},
]


const forceReload = ()=>{
  window.location.reload()
}

defineExpose({tableRef});

onMounted(()=>{
  nextTick(()=>{
    loadData()
  })
})

</script>